package com.lwj.springboot.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LwJ
 * Created by LiWeijie on 2019/7/9.
 */
@MapperScan(basePackages = "com.lwj.springboot.mapper")
@Configuration
public class DynamicDataSourceConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "multipart.datasource.shenzhen")
    public DataSource shenzhen() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "multipart.datasource.huizhou")
    public DataSource huizhou() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 核心动态数据源配置
     *
     * @return
     */
    @Bean
    public DataSource dynamicDataSource() {
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();

        Map<Object, Object> dataSourceMap = new HashMap<>(2);

        //默认数据源
        dataSource.setDefaultTargetDataSource(shenzhen());

        //配置数据源
        dataSourceMap.put(AreaKeyId.SHENZHEN, shenzhen());
        dataSourceMap.put(AreaKeyId.HUIZHOU, huizhou());
        dataSource.setTargetDataSources(dataSourceMap);

        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());

        //此处设置为了解决找不到mapper文件的问题
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory());
    }

    /**
     * 事务管理
     * @return
     */
    @Bean
    public PlatformTransactionManager platformTransactionManager() {

        return new DataSourceTransactionManager(dynamicDataSource());
    }
}
